<!-- app 更新逻辑以及弹窗 -->
<template>
  <uv-popup ref="popRef" :close-on-click-overlay="false" :custom-style="{ overflow: 'visible' }" round="16rpx">
    <view v-if="commonStore.renewInfo" class="w-622rpx box-border pb-64rpx">
      <view class="flex items-center justify-center relative">
        <image
          class="w-full h-350rpx"
          mode="aspectFit"
          src="https://mingtu-resources.oss-cn-shenzhen.aliyuncs.com/mtym-app-assets/app-renew-background.png"
        ></image>
        <view class="absolute left-0 right-0 -top-40rpx">
          <view class="text-center">
            <image
              class="w-380rpx h-250rpx"
              mode="aspectFit"
              src="https://mingtu-resources.oss-cn-shenzhen.aliyuncs.com/mtym-app-assets/app-renew-rocket.png"
            ></image>
          </view>
          <view class="text-center font-bold text-44rpx text-#333333"> 发现新版本 </view>
          <view class="text-center text-28rpx text-#999999"> V{{ commonStore.renewInfo.versionName }} </view>
        </view>
      </view>
      <view class="mb-32rpx px-32rpx">
        <view v-if="!isDow" class="max-h-300rpx py-40rpx overflow-y-auto">
          <view class="text-32rpx text-#333333 font-bold"> 更新内容： </view>
          <view class="mt-10rpx">
            <textarea v-model="tips" auto-height class="text-26rpx text-#666666" disabled></textarea>
          </view>
        </view>
        <view v-else>
          <view class="text-28rpx text-#333333 mb-20rpx"> 正在更新，请稍候... </view>
          <uv-line-progress :percentage="progress" active-color="#007BFF"></uv-line-progress>
        </view>
      </view>
      <view class="flex items-center justify-between px-32rpx">
        <slot name="footer">
          <uv-button
            v-if="showCancelButton"
            :custom-style="{ width: '256rpx', height: '80rpx' }"
            :disabled="isDow"
            custom-text-style="font-size: 28rpx;"
            shape="circle"
            text="取消"
            @click="close"
          ></uv-button>
          <uv-button
            :custom-style="{ width: showCancelButton ? '256rpx' : '550rpx', height: '80rpx' }"
            :disabled="isDow"
            custom-text-style="font-size: 28rpx;"
            shape="circle"
            text="立即体验"
            type="primary"
            @click="handleConfirm"
          ></uv-button>
        </slot>
      </view>
    </view>
  </uv-popup>
</template>

<script setup>
import userCommon from '@/store/common';

const commonStore = userCommon();
watch(
  () => commonStore.renew,
  (val) => {
    if (val && commonStore.renewInfo) {
      init();
    }
  },
  {
    immediate: true
  }
);

// 更新信息
const tips = computed(() => {
  let str = '';
  if (commonStore.renewInfo && commonStore.renewInfo.updateInfo) {
    str = commonStore.renewInfo.updateInfo;
  } else {
    str = '修复一些已知问题';
  }
  return str;
});

// 下载实例
let dtask = null;
// apk 下载进度
const progress = ref(0);
// 是否在下载中
const isDow = ref(false);

const popRef = ref(null);
// 是否显示暂不升级按钮
const showCancelButton = computed(() => {
  return commonStore.renewInfo.forceUpdateFlag !== 1;
});

function init() {
  nextTick(() => {
    setTimeout(() => {
      popRef.value?.open();
    }, 500);
  });
}

function handleConfirm() {
  const system = uni.getSystemInfoSync();

  if (commonStore.renewInfo.updateWay === 2) {
    isDow.value = true;
    progress.value = 0;
    if (/\.wgt$/i.test(commonStore.renewInfo.downloadUrl)) {
      // 热更新
      downloadApp(commonStore.renewInfo.downloadUrl, commonStore.renewInfo.updateWay);
    }
  } else {
    if (system.osName === 'android') {
      if (/\.apk$/i.test(commonStore.renewInfo.downloadUrl)) {
        isDow.value = true;
        progress.value = 0;
        andriodUpdate();
      } else {
        plus.runtime.openURL(commonStore.renewInfo.downloadUrl);
      }
    } else {
      iosUpdate();
    }
  }
}

// 安卓更新逻辑
function andriodUpdate() {
  downloadApp(commonStore.renewInfo.downloadUrl, commonStore.renewInfo.updateWay);
}

// ios更新逻辑
function iosUpdate() {
  plus.runtime.openURL(commonStore.renewInfo.downloadUrl);
}

// 下载app及安装
function downloadApp(downloadUrl, updateWay) {
  dtask = uni.downloadFile({
    url: downloadUrl,
    success: (res) => {
      if (res.statusCode === 200) {
        plus.runtime.install(
          res.tempFilePath,
          {},
          function () {
            reset();
            if (updateWay == 2) {
              plus.runtime.restart();
            }
          },
          function (e) {
            uni.showToast({
              icon: 'none',
              title: '安装失败，请重新点击升级按钮'
            });
            reset();
          }
        );
      } else {
        uni.showToast({
          icon: 'none',
          title: '文件下载失败，请重新点击升级按钮'
        });
        reset();
      }
    },
    fail: (err) => {
      uni.showToast({
        icon: 'none',
        title: '文件下载失败，请重新点击升级按钮'
      });
      reset();
    }
  });
  dtask.onProgressUpdate((res) => {
    progress.value = res.progress;
  });
  // plus.runtime.openURL(downloadUrl)
}

function reset() {
  dtask = null;
  progress.value = 0;
  isDow.value = false;
}

function close() {
  // 点击取消
  // 设置暂不更新，但是重新打开 app 还会提示更新
  commonStore.setRenew(false, null);
  popRef.value.close();
}
</script>

<style lang="scss" scoped></style>
